package cn.gs.util.set;

// @author gs
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Queue;

public class BDBQueue<T> implements Queue<T> {

    BDBMap<Long, T> map;

    public BDBQueue(File dir, String name, Class<T> clazz) {
        map = BDBMap.createAndBindDatabase(dir.getAbsolutePath(), name, Long.class, clazz);
    }

    @Override
    public boolean add(T e) {
        map.put(map.firstKey() + 1, e);
        return true;
    }

    @Override
    public boolean offer(T e) {
        return add(e);
    }

    @Override
    public T remove() {
        T t = map.remove(map.firstKey());
        return t;
    }

    @Override
    public T poll() {
        return map.remove(map.firstKey());
    }

    @Override
    public T element() {
        return map.get(map.firstKey());
    }

    @Override
    public T peek() {
        return map.get(map.firstKey());
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.values().contains(o);
    }

    @Override
    public Iterator iterator() {
        return map.values().iterator();
    }

    @Override
    public T[] toArray() {
        return (T[]) toArray(new Object[map.size()]);
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return map.values().toArray(a);
    }

    @Override
    public boolean remove(Object o) {
        Iterator<Entry<Long, T>> itr = map.entrySet().iterator();
        while (itr.hasNext()) {
            Entry<Long, T> e = itr.next();
            if (e.getValue().equals(o)) {
                itr.remove();
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean containsAll(Collection c) {
        for (Object o : c) {
            if (!contains(o)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
        for (T o : c) {
            add(o);
        }
        return true;
    }

    @Override
    public boolean removeAll(Collection c) {
        for (Object o : c) {
            remove(o);
        }
        return true;
    }

    @Override
    public boolean retainAll(Collection c) {
        boolean modified = false;
        Iterator<T> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

    @Override
    public void clear() {
        map.clear();
    }
}
